<template>
  <div class="video-player">
    <video
      ref="videoElement"
      :poster="poster"
      autoplay
      muted
      playsinline
      controls
      preload="metadata"
      @error="handleError"
      @loadstart="handleLoadStart"
      @canplay="handleCanPlay"
      @loadeddata="handleLoadedData"
      @waiting="handleWaiting"
      @playing="handlePlaying"
      @pause="handlePause"
    >
      您的浏览器不支持视频播放
    </video>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <a-spin size="large" />
      <p>加载中...</p>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-overlay">
      <ExclamationCircleOutlined />
      <p>{{ errorMessage }}</p>
      <a-button @click="retry" size="small">重试</a-button>
    </div>

    <!-- 调试信息 -->
    <div v-if="showDebug" class="debug-info">
      <p><strong>视频URL:</strong> {{ webrtcStreamUrl }}</p>
      <p><strong>播放方式:</strong> {{ webrtcStatus }}</p>
      <p><strong>网络状态:</strong> {{ networkStateText }}</p>
      <p><strong>就绪状态:</strong> {{ readyStateText }}</p>
      <p><strong>错误:</strong> {{ errorInfo }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'

interface Props {
  streamUrl: string
  poster?: string
  showDebug?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  poster: '',
  showDebug: false
})

const videoElement = ref<HTMLVideoElement>()
const loading = ref(false)
const error = ref(false)
const errorMessage = ref('')
const networkState = ref(0)
const readyState = ref(0)

const networkStateText = ref('')
const readyStateText = ref('')
const errorInfo = ref('')

const webrtcStatus = ref('未初始化')
const webrtcReader = ref<any>(null)

// 计算WebRTC流URL
const webrtcStreamUrl = computed(() => {
  return props.streamUrl
})

const updateDebugInfo = () => {
  if (!videoElement.value) return

  const video = videoElement.value
  networkState.value = video.networkState
  readyState.value = video.readyState

  // 网络状态
  const networkStates = [
    'NETWORK_EMPTY',
    'NETWORK_IDLE',
    'NETWORK_LOADING',
    'NETWORK_NO_SOURCE'
  ]
  networkStateText.value = networkStates[video.networkState] || 'UNKNOWN'

  // 就绪状态
  const readyStates = [
    'HAVE_NOTHING',
    'HAVE_METADATA',
    'HAVE_CURRENT_DATA',
    'HAVE_FUTURE_DATA',
    'HAVE_ENOUGH_DATA'
  ]
  readyStateText.value = readyStates[video.readyState] || 'UNKNOWN'

  // 错误信息
  if (video.error) {
    const error = video.error
    errorInfo.value = `Code: ${error.code}, Message: ${error.message}`
  } else {
    errorInfo.value = 'None'
  }
}

const handleError = (event: Event) => {
  const video = event.target as HTMLVideoElement
  const mediaError = video.error
  
  loading.value = false
  error.value = true
  
  if (mediaError) {
    switch (mediaError.code) {
      case MediaError.MEDIA_ERR_ABORTED:
        errorMessage.value = '视频加载被中止'
        break
      case MediaError.MEDIA_ERR_NETWORK:
        errorMessage.value = '网络错误，请检查网络连接和CORS设置'
        break
      case MediaError.MEDIA_ERR_DECODE:
        errorMessage.value = '视频解码错误，格式可能不支持'
        break
      case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
        errorMessage.value = '视频格式不支持或URL无效'
        break
      default:
        errorMessage.value = `未知错误 (${mediaError.code})`
    }
  } else {
    errorMessage.value = '视频加载失败'
  }
  
  updateDebugInfo()
  console.error('视频播放错误详情:', {
    error: mediaError,
    errorCode: mediaError?.code,
    errorMessage: mediaError?.message,
    src: video.src,
    networkState: video.networkState,
    readyState: video.readyState,
    currentSrc: video.currentSrc,
    videoWidth: video.videoWidth,
    videoHeight: video.videoHeight
  })
}

const handleLoadStart = () => {
  loading.value = true
  error.value = false
  updateDebugInfo()
  console.log('视频开始加载')
}

const handleCanPlay = () => {
  loading.value = false
  error.value = false
  updateDebugInfo()
  console.log('视频可以播放')
}

const handleLoadedData = () => {
  loading.value = false
  updateDebugInfo()
  console.log('视频数据加载完成')
}

const handleWaiting = () => {
  console.log('视频缓冲中...')
}

const handlePlaying = () => {
  console.log('视频开始播放')
}

const handlePause = () => {
  console.log('视频暂停')
}

const retry = () => {
  if (videoElement.value) {
    error.value = false
    loading.value = true
    loadWebRtcStream()
  }
}

const loadWebRtcStream = async () => {
  if (!videoElement.value) return
  
  error.value = false
  loading.value = true
  webrtcStatus.value = '加载中...'
  
  try {
    const streamUrl = webrtcStreamUrl.value
    
    // 清理之前的WebRTC读取器
    if (webrtcReader.value) {
      webrtcReader.value.close()
      webrtcReader.value = null
    }
    
    // 检查是否支持MediaMTXWebRTCReader
    if (typeof (window as any).MediaMTXWebRTCReader === 'undefined') {
      // 如果MediaMTXWebRTCReader不存在，尝试加载它
      await loadMediaMTXReader()
    }
    
    webrtcStatus.value = '初始化WebRTC连接...'
    
    // 使用MediaMTX内置的WebRTC读取器
    webrtcReader.value = new (window as any).MediaMTXWebRTCReader({
      url: `${streamUrl}/whep`,
      onError: (err: string) => {
        console.error('WebRTC错误:', err)
        error.value = true
        errorMessage.value = `WebRTC连接错误: ${err}`
        webrtcStatus.value = 'WebRTC错误'
        loading.value = false
      },
      onTrack: (evt: RTCTrackEvent) => {
        console.log('收到WebRTC流:', evt.streams[0])
        if (videoElement.value) {
          videoElement.value.srcObject = evt.streams[0]
          webrtcStatus.value = 'WebRTC流已连接'
          loading.value = false
          error.value = false
        }
      }
    })
    
    webrtcStatus.value = 'WebRTC连接建立中...'
    
  } catch (err) {
    console.error('加载WebRTC流失败:', err)
    error.value = true
    errorMessage.value = `加载WebRTC流失败: ${err}`
    webrtcStatus.value = '加载失败'
    loading.value = false
  }
}

// 加载MediaMTX WebRTC读取器
const loadMediaMTXReader = async () => {
  return new Promise((resolve, reject) => {
    // 检查是否已经加载
    if (typeof (window as any).MediaMTXWebRTCReader !== 'undefined') {
      resolve(true)
      return
    }
    
    // 创建script标签加载reader.js
    const script = document.createElement('script')
    script.src = `${webrtcStreamUrl.value}/reader.js`
    script.onload = () => {
      console.log('MediaMTX WebRTC Reader loaded')
      resolve(true)
    }
    script.onerror = () => {
      console.error('Failed to load MediaMTX WebRTC Reader')
      reject(new Error('无法加载MediaMTX WebRTC读取器'))
    }
    document.head.appendChild(script)
  })
}

// 监听URL变化
watch(() => props.streamUrl, (newUrl) => {
  if (newUrl) {
    error.value = false
    loadWebRtcStream()
  }
})

onMounted(() => {
  if (props.streamUrl) {
    loadWebRtcStream()
  }
})

onUnmounted(() => {
  // 清理WebRTC读取器
  if (webrtcReader.value) {
    webrtcReader.value.close()
    webrtcReader.value = null
  }
  
  // 清理视频元素
  if (videoElement.value) {
    videoElement.value.pause()
    videoElement.value.srcObject = null
  }
})
</script>

<style scoped>
.video-player {
  position: relative;
  width: 100%;
  height: 100%;
  background: #000;
}

.video-player video {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.loading-overlay,
.error-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  z-index: 10;
}

.loading-overlay p,
.error-overlay p {
  margin: 8px 0;
  color: white;
}

.error-overlay .anticon {
  font-size: 32px;
  color: #ff4d4f;
  margin-bottom: 8px;
}

.debug-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px;
  font-size: 12px;
  z-index: 5;
}

.debug-info p {
  margin: 2px 0;
  color: white;
}
</style>
